package com.andnnl.template.param;

import cn.hutool.core.util.StrUtil;

import java.util.Random;

import com.andnnl.template.ParamUtil;

public class StringParamConfig extends BaseParamConfig {
    int minLength;
    int maxLength;

    @Override
    public void validate() {
        if (minLength <= 0 || maxLength < minLength)
            throw new IllegalArgumentException("字符串长度范围无效: " + name + "，minLength=" + minLength + "，maxLength=" + maxLength);
    }

    @Override
    public String generateValue() {
        Random rand = new Random();
        int len = minLength + rand.nextInt(maxLength - minLength + 1);
        return ParamUtil.generateRandomString(len);
    }

    @Override
    public void fromJson(com.fasterxml.jackson.databind.JsonNode node) {
        this.minLength = node.path("minLength").asInt(1);
        this.maxLength = node.path("maxLength").asInt(10);
    }

    public int getMinLength() {
        return minLength;
    }

    public void setMinLength(int minLength) {
        this.minLength = minLength;
    }

    public int getMaxLength() {
        return maxLength;
    }

    @Override
    public boolean validateValue(String value) throws IllegalArgumentException {
        if (StrUtil.isBlank(value)) {
            throw new IllegalArgumentException("字符串参数" + name + "不能为空");
        }
        int length = value.length();
        if (length < minLength || length > maxLength) {
            throw new IllegalArgumentException("字符串参数" + name + "长度必须在" + minLength + "-" + maxLength + "之间，实际长度：" + length);
        }
        return true;
    }

    public void setMaxLength(int maxLength) {
        this.maxLength = maxLength;
    }
}
